<template>
  <div class="purchase-inbound-add-page">
    <el-card shadow="never" class="breadcrumb-card">
      <div class="breadcrumb-content">
        <div class="breadcrumb-title">
          <el-icon class="breadcrumb-icon">
            <Box />
          </el-icon>
          <div>
            <p class="breadcrumb-subtitle">仓库管理 · 采购入库</p>
            <h2 class="breadcrumb-heading">
              {{ isEditMode ? "编辑采购入库" : "新增采购入库" }}
            </h2>
          </div>
        </div>
        <el-breadcrumb :separator-icon="ArrowRight">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>仓库管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/PurchaseInboundList' }">
            采购入库
          </el-breadcrumb-item>
          <el-breadcrumb-item>
            {{ isEditMode ? "编辑" : "新增" }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </el-card>

    <el-card shadow="never" class="form-card">
      <div class="page-header">
        <div class="page-header__content">
          <div class="page-header__title">
            <div class="page-header__icon-wrapper">
              <el-icon class="page-header__icon"><DocumentAdd /></el-icon>
            </div>
            <div class="page-header__text">
              <h2>{{ isEditMode ? "编辑采购入库" : "新增采购入库" }}</h2>
              <p class="page-header__desc">
                {{ isEditMode ? "修改采购入库单信息" : "创建新的采购入库单" }}
              </p>
            </div>
          </div>
          <el-tag
            :type="isEditMode ? 'warning' : 'success'"
            effect="dark"
            size="large"
            class="page-header__tag"
          >
            <el-icon class="tag-icon"><Box /></el-icon>
            {{ isEditMode ? "编辑模式" : "新增模式" }}
          </el-tag>
        </div>
      </div>

      <el-form
        ref="formRef"
        :model="formModel"
        :rules="rules"
        label-width="120px"
        class="purchase-inbound-form"
      >
        <!-- 基础信息 -->
        <div class="form-section">
          <div class="section-header">
            <div class="section-header__main">
              <div class="section-header__icon">
                <el-icon><DocumentAdd /></el-icon>
              </div>
              <div>
                <p class="section-title">基础信息</p>
                <p class="section-subtitle">完善入库单的基础内容</p>
              </div>
            </div>
            <el-tag type="success" effect="light" size="small">
              必填字段
            </el-tag>
          </div>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="入库单编号" prop="inboundOrderNo" required>
                <div class="system-code-field">
                  <div class="system-code-row">
                    <el-input
                      v-model="formModel.inboundOrderNo"
                      placeholder="请输入/自动生成"
                      :disabled="isSystemNo"
                      clearable
                      class="system-code-input"
                      style="width: 230px"
                    >
                      <template #prefix>
                        <el-icon class="system-code-prefix"
                          ><Tickets
                        /></el-icon>
                      </template>
                    </el-input>
                    <el-tooltip
                      content="复制当前编号"
                      placement="top"
                      :hide-after="0"
                    >
                      <el-button
                        circle
                        text
                        class="system-code-btn"
                        :disabled="!formModel.inboundOrderNo"
                        @click="handleCopySystemCode"
                      >
                        <el-icon><CopyDocument /></el-icon>
                      </el-button>
                    </el-tooltip>
                    <el-tooltip
                      content="重新生成系统编号"
                      placement="top"
                      :hide-after="0"
                    >
                      <el-button
                        circle
                        text
                        class="system-code-btn"
                        :disabled="!isSystemNo"
                        @click="handleRegenerateSystemCode"
                      >
                        <el-icon><Refresh /></el-icon>
                      </el-button>
                    </el-tooltip>
                  </div>
                  <div class="system-code-controls">
                    <el-switch
                      v-model="isSystemNo"
                      active-text=""
                      inactive-text=""
                      @change="handleSystemNoChange"
                    />
                    <span
                      class="system-code-status"
                      :class="{ 'is-auto': isSystemNo }"
                    >
                      <el-icon>
                        <component :is="isSystemNo ? Lightning : EditPen" />
                      </el-icon>
                      {{ isSystemNo ? "系统自动编号" : "允许手动填写" }}
                    </span>
                  </div>
                  <p class="system-code-hint">
                    {{
                      isSystemNo
                        ? "编号由时间戳、毫秒与唯一校验因子组成，确保全局唯一。"
                        : "关闭后可手动输入/粘贴外部编号，需自行确保唯一性。"
                    }}
                  </p>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库单名称" prop="inboundOrderName" required>
                <el-input
                  v-model="formModel.inboundOrderName"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="入库日期" prop="inboundDate">
                <el-date-picker
                  v-model="formModel.inboundDate"
                  type="date"
                  placeholder="请选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购单名称" prop="purchaseOrderName">
                <el-input
                  v-model="formModel.purchaseOrderName"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="采购单号" prop="purchaseOrderNo">
                <el-input
                  v-model="formModel.purchaseOrderNo"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商" prop="supplierName">
                <div class="supplier-select-field">
                  <el-input
                    v-model="formModel.supplierName"
                    placeholder="请选择供应商"
                    clearable
                    readonly
                  />
                  <el-button
                    type="primary"
                    link
                    class="supplier-select-btn"
                    @click="handleOpenSupplierDialog"
                  >
                    <el-icon><Grid /></el-icon>
                    选择
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="来料检验名称" prop="materialInspectName">
                <div class="inspection-select-field">
                  <el-input
                    v-model="formModel.materialInspectName"
                    placeholder="请选择来料检验单"
                    readonly
                    clearable
                  />
                  <el-button
                    type="primary"
                    link
                    class="inspection-select-btn"
                    @click="handleOpenInspectionDialog"
                  >
                    <el-icon><Grid /></el-icon>
                    选择
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="来料检验单号" prop="materialInspectNo">
                <el-input
                  v-model="formModel.materialInspectNo"
                  placeholder="通过选择来料检验单自动带出"
                  readonly
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

         

          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="formModel.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入"
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 入库明细 -->
        <div class="form-section detail-section">
          <div class="section-header">
            <div class="section-header__main">
              <div class="section-header__icon section-header__icon--detail">
                <el-icon><List /></el-icon>
              </div>
              <div>
                <p class="section-title">入库明细</p>
                <p class="section-subtitle">添加需要入库的物料信息</p>
              </div>
            </div>
            <div class="section-header__actions">
              <el-tag
                type="info"
                effect="light"
                size="small"
                class="detail-count-tag"
              >
                共 {{ formModel.detail.length }} 项
              </el-tag>
              <el-button
                type="primary"
                :icon="Plus"
                size="default"
                @click="handleAddDetail"
                class="add-detail-btn"
              >
                添加明细
              </el-button>
            </div>
          </div>

          <div v-if="formModel.detail.length > 0" class="detail-list">
            <div
              v-for="(item, index) in formModel.detail"
              :key="index"
              class="detail-item"
            >
              <div class="detail-item-header">
                <div class="detail-item-number-wrapper">
                  <span class="detail-item-number">明细 {{ index + 1 }}</span>
                  <el-tag
                    type="info"
                    effect="plain"
                    size="small"
                    class="detail-item-tag"
                  >
                    物料信息
                  </el-tag>
                </div>
                <el-button
                  type="danger"
                  link
                  size="default"
                  :icon="Delete"
                  @click="handleRemoveDetail(index)"
                  class="delete-detail-btn"
                >
                  删除
                </el-button>
              </div>
              <el-form :model="item" label-width="100px" class="detail-form">
                <el-row :gutter="24">
                  <!-- 左列 -->
                  <el-col :span="12">
                    <el-form-item label="物料名称" required>
                      <el-input
                        v-model="item.materialName"
                        placeholder="请输入"
                        clearable
                      />
                    </el-form-item>
                    <el-form-item label="规格型号">
                      <el-input
                        v-model="item.specification"
                        placeholder="请输入"
                        clearable
                      />
                    </el-form-item>
                    <el-form-item label="生产日期">
                      <el-date-picker
                        v-model="item.productionDate"
                        type="date"
                        placeholder="请选择日期"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                        style="width: 100%"
                      />
                    </el-form-item>
                    <el-form-item label="批次号" required>
                      <div class="batch-select-field">
                        <el-input
                          v-model="item.batchNo"
                          placeholder="请选择批次号"
                          clearable
                        />
                        <el-button
                          type="primary"
                          link
                          class="batch-select-btn"
                          @click="handleOpenBatchDialog(index)"
                        >
                          <el-icon><Grid /></el-icon>
                          选择
                        </el-button>
                      </div>
                    </el-form-item>
                    <el-form-item label="仓库名称">
                      <div class="warehouse-select-field">
                        <el-input
                          v-model="item.warehouseName"
                          placeholder="请选择仓库/库区/库位"
                          readonly
                          clearable
                        />
                        <el-button
                          type="primary"
                          link
                          class="warehouse-select-btn"
                          @click="handleOpenWarehouseDialog(index)"
                        >
                          <el-icon><Grid /></el-icon>
                          选择
                        </el-button>
                      </div>
                    </el-form-item>
                  </el-col>
                  <!-- 右列 -->
                  <el-col :span="12">
                    <el-form-item label="物料编号" required>
                      <el-input
                        v-model="item.materialNo"
                        placeholder="请输入"
                        clearable
                      />
                    </el-form-item>
                    <el-form-item label="单位">
                      <el-input
                        v-model="item.unit"
                        placeholder="请输入"
                        clearable
                      />
                    </el-form-item>
                    <el-form-item label="到期日期">
                      <el-date-picker
                        v-model="item.expiryDate"
                        type="date"
                        placeholder="请选择日期"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                        style="width: 100%"
                      />
                    </el-form-item>
                    <el-form-item label="入库数量" required>
                      <el-input-number
                        v-model="item.inboundQuantity"
                        :min="0"
                        :precision="2"
                        placeholder="请输入"
                        style="width: 100%"
                      />
                    </el-form-item>
                    <el-form-item label="仓库负责人">
                      <el-input
                        v-model="item.warehousePrincipal"
                        placeholder="通过选择仓库自动带出"
                        readonly
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>

          <el-empty
            v-else
            description='暂无明细数据，请点击上方"添加明细"按钮添加'
            :image-size="100"
            class="empty-detail"
          />
        </div>
      </el-form>

      <div class="form-actions">
        <el-button size="large" @click="handleCancel" class="cancel-btn">
          <el-icon><Close /></el-icon>
          取消
        </el-button>
        <el-button
          type="primary"
          size="large"
          @click="handleSubmit"
          :loading="submitLoading"
          class="submit-btn"
        >
          <el-icon v-if="!submitLoading"><Check /></el-icon>
          {{ submitLoading ? "提交中..." : "确定提交" }}
        </el-button>
      </div>
    </el-card>

    <el-dialog
      v-model="batchDialogVisible"
      title="选择批次号"
      width="1000px"
      class="batch-dialog"
      :close-on-click-modal="false"
    >
      <div class="batch-dialog-toolbar">
        <el-input
          v-model="batchSearchCode"
          placeholder="请输入批次号"
          clearable
          @keyup.enter="handleBatchSearch"
        />
        <el-button type="primary" @click="handleBatchSearch">查询</el-button>
        <el-button @click="handleBatchReset">重置</el-button>
      </div>
      <el-table
        :data="batchTableData"
        v-loading="batchListLoading"
        height="360"
        border
        class="batch-dialog-table"
        style="width: 1000px"
      >
        <el-table-column width="60" align="center">
          <template #default="{ row }">
            <el-radio
              v-model="selectedBatchId"
              :label="row.id"
              @change="() => handleBatchRowSelect(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="序号" width="80" align="center">
          <template #default="{ $index }">
            {{
              $index +
              1 +
              (batchPagination.pageIndex - 1) * batchPagination.pageSize
            }}
          </template>
        </el-table-column>
        <el-table-column prop="batchCode" label="批次号" min-width="140" />
        <el-table-column label="生产日期" min-width="140">
          <template #default="{ row }">
            {{ formatBatchDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="到期日期" min-width="140">
          <template #default="{ row }">
            {{ formatBatchDate(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column label="库存" width="100" align="center">
          <template #default="{ row }">
            {{ row.inventory ?? "-" }}
          </template>
        </el-table-column>
      </el-table>
      <div class="batch-dialog-pagination">
        <el-pagination
          background
          layout="prev, pager, next, jumper, ->, total"
          :current-page="batchPagination.pageIndex"
          :page-size="batchPagination.pageSize"
          :total="batchPagination.total"
          @current-change="handleBatchPageChange"
        />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBatchConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="supplierDialogVisible"
      title="选择供应商"
      width="1000px"
      class="supplier-dialog"
      :close-on-click-modal="false"
    >
      <div class="supplier-dialog-toolbar">
        <el-input
          v-model="supplierSearchForm.keyword"
          placeholder="请输入供应商编号/名称"
          clearable
          @keyup.enter="handleSupplierSearch"
        />
        <el-select
          v-model="supplierSearchForm.grade"
          placeholder="请选择供应商等级"
          clearable
          filterable
          :loading="supplierGradeLoading"
        >
          <el-option
            v-for="item in supplierGradeOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
        <el-button @click="handleSupplierReset">重置</el-button>
        <el-button type="primary" @click="handleSupplierSearch">查询</el-button>
      </div>
      <el-table
        :data="supplierTableData"
        v-loading="supplierListLoading"
        border
        height="360"
        class="supplier-dialog-table"
        style="width: 100%"
      >
        <el-table-column width="60" align="center">
          <template #default="{ row }">
            <el-radio
              v-model="selectedSupplierId"
              :label="row.id"
              @change="() => handleSupplierRowSelect(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="序号" width="80" align="center">
          <template #default="{ $index }">
            {{
              $index +
              1 +
              (supplierPagination.pageIndex - 1) * supplierPagination.pageSize
            }}
          </template>
        </el-table-column>
        <el-table-column prop="code" label="供应商编号" min-width="160" />
        <el-table-column prop="name" label="供应商名称" min-width="180" />
        <el-table-column prop="grade" label="供应商等级" min-width="160" />
        <el-table-column prop="contact" label="联系人" min-width="140" />
        <el-table-column prop="phone" label="联系电话" min-width="160" />
      </el-table>
      <div class="supplier-dialog-pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="supplierPagination.pageIndex"
          :page-size="supplierPagination.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="supplierPagination.total"
          @current-change="handleSupplierPageChange"
          @size-change="handleSupplierPageSizeChange"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="supplierDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSupplierConfirm"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="warehouseDialogVisible"
      title="选择仓库"
      width="1000px"
      class="warehouse-dialog"
      :close-on-click-modal="false"
    >
      <div class="warehouse-dialog-summary">
        仓库名称：{{ selectedWarehouseOption?.name || "未选择" }}　 库区名称：{{
          selectedReservoirOption?.name || "未选择"
        }}　 库位名称：{{ selectedSeatOption?.name || "未选择" }}
      </div>
      <div class="warehouse-dialog-columns">
        <div class="warehouse-column">
          <div class="column-title">仓库名称</div>
          <el-input
            v-model="warehouseSearchForm.warehouse"
            placeholder="请输入仓库名称"
            clearable
            @keyup.enter="handleWarehouseSearchSubmit('warehouse')"
          >
            <template #suffix>
              <el-icon
                class="column-search-icon"
                @click.stop="handleWarehouseSearchSubmit('warehouse')"
              >
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-scrollbar class="column-list">
            <div
              v-for="item in warehouseOptions"
              :key="item.id"
              :class="[
                'column-option',
                { active: selectedWarehouseId === item.id },
              ]"
              @click="selectWarehouseOption(item)"
            >
              {{ item.name }}
            </div>
            <el-empty
              v-if="!warehouseOptions.length && !warehouseLoading"
              description="暂无数据"
              :image-size="60"
            />
          </el-scrollbar>
        </div>
        <div class="warehouse-column">
          <div class="column-title">库区名称</div>
          <el-input
            v-model="warehouseSearchForm.reservoir"
            placeholder="请输入库区名称"
            clearable
            @keyup.enter="handleWarehouseSearchSubmit('reservoir')"
          >
            <template #suffix>
              <el-icon
                class="column-search-icon"
                @click.stop="handleWarehouseSearchSubmit('reservoir')"
              >
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-scrollbar class="column-list">
            <div
              v-for="item in reservoirOptions"
              :key="item.id"
              :class="[
                'column-option',
                { active: selectedReservoirId === item.id },
              ]"
              @click="selectReservoirOption(item)"
            >
              {{ item.name }}
            </div>
            <el-empty
              v-if="!reservoirOptions.length && !reservoirLoading"
              description="暂无数据"
              :image-size="60"
            />
          </el-scrollbar>
        </div>
        <div class="warehouse-column">
          <div class="column-title">库位名称</div>
          <el-input
            v-model="warehouseSearchForm.seat"
            placeholder="请输入库位名称"
            clearable
            @keyup.enter="handleWarehouseSearchSubmit('seat')"
          >
            <template #suffix>
              <el-icon
                class="column-search-icon"
                @click.stop="handleWarehouseSearchSubmit('seat')"
              >
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-scrollbar class="column-list">
            <div
              v-for="item in seatOptions"
              :key="item.id"
              :class="['column-option', { active: selectedSeatId === item.id }]"
              @click="selectSeatOption(item)"
            >
              {{ item.name }}
            </div>
            <el-empty
              v-if="!seatOptions.length && !seatLoading"
              description="暂无数据"
              :image-size="60"
            />
          </el-scrollbar>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="warehouseDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleWarehouseConfirm"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 来料检验选择对话框 -->
    <el-dialog
      v-model="inspectionDialogVisible"
      title="选择来料检验单"
      width="1200px"
      class="inspection-dialog"
      :close-on-click-modal="false"
    >
      <!-- 搜索筛选区域 -->
      <div class="inspection-dialog-toolbar">
        <el-input
          v-model="inspectionSearchForm.keyword"
          placeholder="请输入来料单编号/名称"
          clearable
          @keyup.enter="handleInspectionSearch"
          style="width: 280px"
        />
        <el-input
          v-model="inspectionSearchForm.materialKeyword"
          placeholder="请输入物料编号/名称"
          clearable
          @keyup.enter="handleInspectionSearch"
          style="width: 280px"
        />
        <el-date-picker
          v-model="inspectionSearchForm.incomingDate"
          type="date"
          placeholder="请选择来料日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          clearable
          style="width: 200px"
        />
        <el-button @click="handleInspectionReset">重置</el-button>
        <el-button type="primary" @click="handleInspectionSearch"
          >查询</el-button
        >
      </div>

      <!-- 表格 -->
      <el-table
        :data="inspectionTableData"
        v-loading="inspectionListLoading"
        height="400px"
        border
        class="inspection-dialog-table"
        style="width: 100%"
      >
        <el-table-column width="60" align="center">
          <template #default="{ row }">
            <el-radio
              v-model="selectedInspectionId"
              :label="row.id"
              @change="handleInspectionRowSelect(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="序号" width="80" align="center">
          <template #default="{ $index }">
            {{
              $index +
              1 +
              (inspectionPagination.pageIndex - 1) *
                inspectionPagination.pageSize
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="inspectionname"
          label="检验单名称"
          min-width="160"
        />
        <el-table-column
          prop="inspectioncode"
          label="检验单号"
          min-width="160"
        />
        <el-table-column prop="materialname" label="物料名称" min-width="140" />
        <el-table-column prop="materialcode" label="物料编号" min-width="140" />
        <el-table-column
          prop="specification"
          label="规格型号"
          min-width="120"
        />
        <el-table-column prop="unit" label="单位" width="100" />
        <el-table-column prop="batchno" label="批次号" min-width="140" />
        <el-table-column label="来料日期" min-width="120">
          <template #default="{ row }">
            {{ formatInspectionDate(row.incomingdate) }}
          </template>
        </el-table-column>
        <el-table-column label="检验日期" min-width="120">
          <template #default="{ row }">
            {{ formatInspectionDate(row.inspectiondate) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="inspection-dialog-pagination">
        <div class="pagination-total">
          共 {{ inspectionPagination.total }} 条
        </div>
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :current-page="inspectionPagination.pageIndex"
          :page-size="inspectionPagination.pageSize"
          :total="inspectionPagination.total"
          @current-change="handleInspectionPageChange"
        />
      </div>

      <!-- 底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="inspectionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleInspectionConfirm"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import {
  ArrowRight,
  DocumentAdd,
  Box,
  Plus,
  Delete,
  Grid,
  List,
  Close,
  Check,
  Search,
  Refresh,
  CopyDocument,
  Lightning,
  EditPen,
  Tickets,
} from "@element-plus/icons-vue";
import https from "@/Http/http";

const router = useRouter();
const route = useRoute();
const formRef = ref<FormInstance>();
const submitLoading = ref(false);
const isSystemNo = ref(false);
const isEditMode = ref(false);
const editId = ref<number | null>(null);

// 编码生成计数器，确保每次生成都不同
let codeGenerationCounter = 0;

// 生成系统编号（基于年月日时分秒）
const generateSystemCode = (): string => {
  const now = new Date();
  const pad = (n: number, len: number = 2) => `${n}`.padStart(len, "0");

  // 获取年月日时分秒
  const year = now.getFullYear();
  const month = pad(now.getMonth() + 1);
  const day = pad(now.getDate());
  const hours = pad(now.getHours());
  const minutes = pad(now.getMinutes());
  const seconds = pad(now.getSeconds());
  const milliseconds = now.getMilliseconds();

  // 获取时间戳和微秒
  const timestamp = Date.now();
  let microSeconds = 0;
  if (typeof performance !== "undefined" && performance.now) {
    const perfNow = performance.now();
    microSeconds = Math.floor((perfNow % 1) * 1000);
  } else {
    microSeconds = Math.floor(Math.random() * 1000);
  }

  // 递增计数器
  codeGenerationCounter = (codeGenerationCounter + 1) % 100000;

  // 生成唯一因子
  const timestampSuffix = timestamp.toString().slice(-4).padStart(4, "0");
  const microSecondsStr = microSeconds.toString().padStart(3, "0");
  const counterStr = codeGenerationCounter.toString().padStart(5, "0");
  const counterSuffix = counterStr.slice(-3);
  const uniqueFactor = (
    timestampSuffix +
    microSecondsStr +
    counterSuffix
  ).slice(-6);

  // 格式：CG + 年月日(8位) + 时分秒(6位) + 毫秒(3位) + 唯一因子(6位)
  const msStr = pad(milliseconds, 3);
  return (
    "CG" + year + month + day + hours + minutes + seconds + msStr + uniqueFactor
  );
};

const assignNewInboundCode = () => {
  formModel.inboundOrderNo = generateSystemCode();
  console.log(
    "生成的入库单编号:",
    formModel.inboundOrderNo,
    "计数器:",
    codeGenerationCounter
  );
};

// 处理系统编号开关变化
const handleSystemNoChange = (value: boolean) => {
  if (value) {
    formModel.inboundOrderNo = "";
    setTimeout(assignNewInboundCode, 0);
  } else {
    formModel.inboundOrderNo = "";
  }
};

const handleRegenerateSystemCode = () => {
  if (!isSystemNo.value) {
    ElMessage.info("当前为手动模式，开启系统编号后才可自动生成");
    return;
  }
  formModel.inboundOrderNo = "";
  setTimeout(() => {
    assignNewInboundCode();
    ElMessage.success("已重新生成系统编号");
  }, 0);
};

const copyTextToClipboard = async (text: string) => {
  if (!text) return;

  const safeNavigator =
    typeof navigator !== "undefined"
      ? (navigator as Navigator & {
          clipboard?: { writeText?: (value: string) => Promise<void> };
        })
      : undefined;

  if (safeNavigator?.clipboard?.writeText) {
    await safeNavigator.clipboard.writeText(text);
    return;
  }

  if (typeof document === "undefined") {
    throw new Error("当前环境不支持复制");
  }

  const textArea = document.createElement("textarea");
  textArea.value = text;
  textArea.style.position = "fixed";
  textArea.style.opacity = "0";
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();
  document.execCommand("copy");
  document.body.removeChild(textArea);
};

const handleCopySystemCode = async () => {
  if (!formModel.inboundOrderNo) {
    ElMessage.warning("暂无编号可复制");
    return;
  }
  try {
    await copyTextToClipboard(formModel.inboundOrderNo);
    ElMessage.success("编号已复制");
  } catch (error) {
    console.error("复制失败", error);
    ElMessage.error("复制失败，请手动复制");
  }
};

// 明细项接口
interface DetailItem {
  id?: number | null;
  inboundOrderId: number;
  materialName: string;
  materialNo: string;
  specification: string;
  unit: string;
  productionDate: string | null;
  expiryDate: string | null;
  batchNo: string;
  inboundQuantity: number;
  warehouseName: string;
  warehousePrincipal: string;
}

// 表单数据接口
interface PurchaseInboundForm {
  inboundOrderNo: string;
  isSystemNo: boolean;
  inboundOrderName: string;
  inboundDate: string | null;
  purchaseOrderName: string;
  purchaseOrderNo: string;
  supplierName: string | null;
  materialInspectName: string;
  materialInspectNo: string;
  materialName: string;
  materialCode: string;
  specification: string;
  unit: string;
  remark: string;
  detail: DetailItem[];
}

// 来料检验DTO接口
interface IncomingInspectionDto {
  id: number;
  inspectioncode: string;
  inspectionname?: string;
  incomingdate?: string;
  inspectiondate?: string;
  materialname?: string;
  materialcode?: string;
  specification?: string;
  unit?: string;
  batchno?: string;
}

interface BatchItem {
  id: number;
  batchCode: string;
  createTime: string | null;
  endTime: string | null;
  inventory: number | null;
}

interface SupplierRow {
  id: number;
  code: string;
  name: string;
  grade: string;
  contact: string;
  phone: string;
}

interface WarehouseOption {
  id: number;
  name: string;
  principal?: string;
}

interface ReservoirOption {
  id: number;
  name: string;
  warehouseId?: number;
}

interface SeatOption {
  id: number;
  name: string;
  warehouseId?: number;
  reservoirId?: number;
}

const formModel = reactive<PurchaseInboundForm>({
  inboundOrderNo: "",
  isSystemNo: false,
  inboundOrderName: "",
  inboundDate: null,
  purchaseOrderName: "",
  purchaseOrderNo: "",
  supplierName: null,
  materialInspectName: "",
  materialInspectNo: "",
  materialName: "",
  materialCode: "",
  specification: "",
  unit: "",
  remark: "",
  detail: [],
});

// 表单验证规则
const rules = reactive<FormRules>({
  inboundOrderNo: [
    { required: true, message: "入库单编号不能为空", trigger: "blur" },
  ],
  inboundOrderName: [
    { required: true, message: "入库单名称不能为空", trigger: "blur" },
  ],
});

const batchDialogVisible = ref(false);
const batchListLoading = ref(false);
const batchTableData = ref<BatchItem[]>([]);
const batchSearchCode = ref("");
const batchPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
});
const selectedBatchId = ref<number | null>(null);
const selectedBatchRow = ref<BatchItem | null>(null);
const currentBatchDetailIndex = ref<number | null>(null);

const supplierDialogVisible = ref(false);
const supplierListLoading = ref(false);
const supplierTableData = ref<SupplierRow[]>([]);
const supplierSearchForm = reactive({
  keyword: "",
  grade: "",
});
const supplierPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
});
const selectedSupplierId = ref<number | null>(null);
const selectedSupplierRow = ref<SupplierRow | null>(null);
const supplierGradeOptions = ref<string[]>([]);
const supplierGradeLoading = ref(false);

const warehouseDialogVisible = ref(false);
const warehouseOptions = ref<WarehouseOption[]>([]);
const reservoirOptions = ref<ReservoirOption[]>([]);
const seatOptions = ref<SeatOption[]>([]);
const warehouseSearchForm = reactive({
  warehouse: "",
  reservoir: "",
  seat: "",
});
const selectedWarehouseId = ref<number | null>(null);
const selectedReservoirId = ref<number | null>(null);
const selectedSeatId = ref<number | null>(null);
const selectedWarehouseOption = ref<WarehouseOption | null>(null);
const selectedReservoirOption = ref<ReservoirOption | null>(null);
const selectedSeatOption = ref<SeatOption | null>(null);
const currentWarehouseDetailIndex = ref<number | null>(null);
const warehouseLoading = ref(false);
const reservoirLoading = ref(false);
const seatLoading = ref(false);

// 来料检验选择对话框相关
const inspectionDialogVisible = ref(false);
const inspectionListLoading = ref(false);
const inspectionTableData = ref<IncomingInspectionDto[]>([]);
const inspectionSearchForm = reactive({
  keyword: "", // 来料单编号/名称
  materialKeyword: "", // 物料编号/名称
  incomingDate: null as string | null, // 来料日期
});
const inspectionPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
});
const selectedInspectionId = ref<number | null>(null);
const selectedInspectionRow = ref<IncomingInspectionDto | null>(null);

const formatBatchDate = (value: string | null | undefined): string | null => {
  if (typeof value !== "string" || !value) return null;
  const [datePart] = value.split("T");
  return datePart ?? null;
};

const normalizeBatchItem = (item: any): BatchItem => ({
  id: item.id ?? item.Id ?? 0,
  batchCode: item.batchCode ?? item.BatchCode ?? "",
  createTime: item.createTime ?? item.CreateTime ?? null,
  endTime: item.endTime ?? item.EndTime ?? null,
  inventory: item.inventory ?? item.Inventory ?? null,
});

const fetchBatchList = async () => {
  batchListLoading.value = true;
  try {
    const params: Record<string, any> = {
      PageIndex: batchPagination.pageIndex,
      PageSize: batchPagination.pageSize,
    };
    if (batchSearchCode.value.trim()) {
      params.BatchCode = batchSearchCode.value.trim();
    }
    const res = await https.Reads.get("/Warehouse/BatchList", { params });
    const payload = res.data || {};
    const rawList = payload.data ?? payload.Data ?? [];
    batchTableData.value = Array.isArray(rawList)
      ? rawList.map((item: any) => normalizeBatchItem(item))
      : [];
    batchPagination.total =
      payload.totalCount ?? payload.TotalCount ?? batchTableData.value.length;
  } catch (error: any) {
    console.error("获取批次列表失败", error);
    const msg =
      error?.response?.data?.msg ||
      error?.message ||
      "获取批次列表失败，请稍后再试";
    ElMessage.error(msg);
    batchTableData.value = [];
    batchPagination.total = 0;
  } finally {
    batchListLoading.value = false;
  }
};

const handleOpenBatchDialog = (detailIndex: number) => {
  currentBatchDetailIndex.value = detailIndex;
  batchDialogVisible.value = true;
  selectedBatchId.value = null;
  selectedBatchRow.value = null;
  batchPagination.pageIndex = 1;
  fetchBatchList();
};

const handleBatchSearch = () => {
  batchPagination.pageIndex = 1;
  fetchBatchList();
};

const handleBatchReset = () => {
  batchSearchCode.value = "";
  handleBatchSearch();
};

const handleBatchPageChange = (page: number) => {
  batchPagination.pageIndex = page;
  fetchBatchList();
};

const handleBatchRowSelect = (row: BatchItem) => {
  selectedBatchRow.value = row;
};

const handleBatchConfirm = () => {
  if (currentBatchDetailIndex.value === null) {
    batchDialogVisible.value = false;
    return;
  }

  const batchRow = selectedBatchRow.value;
  if (!batchRow) {
    ElMessage.warning("请选择批次号");
    return;
  }

  const detail = formModel.detail[currentBatchDetailIndex.value];
  if (!detail) {
    ElMessage.error("无法定位当前明细，请重新打开批次选择");
    return;
  }

  detail.batchNo = batchRow.batchCode;
  if (batchRow.createTime) {
    detail.productionDate = formatBatchDate(batchRow.createTime);
  }
  if (batchRow.endTime) {
    detail.expiryDate = formatBatchDate(batchRow.endTime);
  }
  batchDialogVisible.value = false;
};

const normalizeSupplierRow = (row: any): SupplierRow => ({
  id: Number(row.id ?? row.ID ?? row.supplierId ?? 0),
  code:
    row.suppnumber ??
    row.suppNumber ??
    row.supplierCode ??
    row.code ??
    row.custnumber ??
    row.custNumber ??
    "",
  name:
    row.suppname ??
    row.suppName ??
    row.supplierName ??
    row.name ??
    row.custname ??
    row.custName ??
    "",
  grade: row.suppgrade ?? row.suppGrade ?? row.grade ?? row.custgrade ?? "",
  contact:
    row.supppeople ??
    row.suppPeople ??
    row.linkman ??
    row.people ??
    row.contact ??
    "",
  phone: row.phone ?? row.telephone ?? row.tel ?? row.mobile ?? "",
});

const fetchSupplierList = async () => {
  supplierListLoading.value = true;
  supplierGradeLoading.value = true;
  try {
    const params: Record<string, any> = {
      pageindex: supplierPagination.pageIndex,
      pagesize: supplierPagination.pageSize,
    };
    if (supplierSearchForm.keyword.trim()) {
      params.name = supplierSearchForm.keyword.trim();
    }
    if (supplierSearchForm.grade) {
      params.grade = supplierSearchForm.grade;
    }
    const res = await https.Reads.get("/Supplier/ShowSupplier", { params });
    const payload = res.data || {};
    const rawList = payload.data ?? payload.Data ?? [];
    supplierTableData.value = Array.isArray(rawList)
      ? rawList.map((item: any) => normalizeSupplierRow(item))
      : [];
    supplierPagination.total =
      payload.totalCount ??
      payload.TotalCount ??
      supplierTableData.value.length;
    const gradeSet = new Set<string>(
      supplierTableData.value
        .map((item) => item.grade)
        .filter((item): item is string => Boolean(item && item.trim()))
    );
    supplierGradeOptions.value = Array.from(gradeSet).sort();
  } catch (error: any) {
    console.error("获取供应商列表失败", error);
    const msg =
      error?.response?.data?.msg ||
      error?.message ||
      "获取供应商列表失败，请稍后再试";
    ElMessage.error(msg);
    supplierTableData.value = [];
    supplierPagination.total = 0;
  } finally {
    supplierListLoading.value = false;
    supplierGradeLoading.value = false;
  }
};

const handleOpenSupplierDialog = () => {
  supplierDialogVisible.value = true;
  supplierPagination.pageIndex = 1;
  selectedSupplierId.value = null;
  selectedSupplierRow.value = null;
  fetchSupplierList();
};

const handleSupplierSearch = () => {
  supplierPagination.pageIndex = 1;
  fetchSupplierList();
};

const handleSupplierReset = () => {
  supplierSearchForm.keyword = "";
  supplierSearchForm.grade = "";
  handleSupplierSearch();
};

const handleSupplierPageChange = (page: number) => {
  supplierPagination.pageIndex = page;
  fetchSupplierList();
};

const handleSupplierPageSizeChange = (size: number) => {
  supplierPagination.pageSize = size;
  supplierPagination.pageIndex = 1;
  fetchSupplierList();
};

const handleSupplierRowSelect = (row: SupplierRow) => {
  selectedSupplierId.value = row.id;
  selectedSupplierRow.value = row;
};

const handleSupplierConfirm = () => {
  if (!selectedSupplierRow.value) {
    ElMessage.warning("请选择供应商");
    return;
  }
  formModel.supplierName = selectedSupplierRow.value.name;
  supplierDialogVisible.value = false;
};

const normalizeWarehouseOption = (item: any): WarehouseOption => ({
  id: item.id ?? item.Id ?? 0,
  name:
    item.warehousenmae ??
    item.warehousename ??
    item.warehouseName ??
    item.Warehousenmae ??
    item.name ??
    "",
  principal:
    item.principal ??
    item.Principal ??
    item.warehousePrincipal ??
    item.WarehousePrincipal ??
    "",
});

const normalizeReservoirOption = (item: any): ReservoirOption => ({
  id: item.id ?? item.Id ?? 0,
  name:
    item.reservoirnmae ??
    item.reservoirname ??
    item.Reservoirnmae ??
    item.name ??
    "",
  warehouseId: item.warehouseid ?? item.Warehouseid ?? item.warehouseId,
});

const normalizeSeatOption = (item: any): SeatOption => ({
  id: item.id ?? item.Id ?? 0,
  name: item.seatnmae ?? item.seatname ?? item.Seatnmae ?? item.name ?? "",
  warehouseId: item.warehouseid ?? item.Warehouseid ?? item.warehouseId,
  reservoirId: item.reservoirid ?? item.Reservoirid ?? item.reservoirId,
});

const fetchWarehouseOptions = async () => {
  warehouseLoading.value = true;
  try {
    const params: Record<string, any> = {
      Pageindex: 1,
      PageSize: 1000,
      Warehousenmae: warehouseSearchForm.warehouse || undefined,
      WarehousenmaeLike: warehouseSearchForm.warehouse || undefined,
    };
    const res = await https.Reads.get("/Warehouse/WarehouseList", { params });
    const payload = res.data || {};
    const rawList = payload.data ?? payload.Data ?? [];
    warehouseOptions.value = Array.isArray(rawList)
      ? rawList.map((item: any) => normalizeWarehouseOption(item))
      : [];
  } catch (error) {
    console.error("获取仓库列表失败", error);
    warehouseOptions.value = [];
  } finally {
    warehouseLoading.value = false;
  }
};

const fetchReservoirOptions = async () => {
  reservoirLoading.value = true;
  try {
    const params: Record<string, any> = {
      Pageindex: 1,
      PageSize: 1000,
      Reservoirnmae: warehouseSearchForm.reservoir || undefined,
    };
    if (selectedWarehouseId.value) {
      params.Warehouseid = selectedWarehouseId.value;
    }
    const res = await https.Reads.get("/Warehouse/ReservoirList", { params });
    const payload = res.data || {};
    const rawList = payload.data ?? payload.Data ?? [];
    reservoirOptions.value = Array.isArray(rawList)
      ? rawList.map((item: any) => normalizeReservoirOption(item))
      : [];
  } catch (error) {
    console.error("获取库区列表失败", error);
    reservoirOptions.value = [];
  } finally {
    reservoirLoading.value = false;
  }
};

const fetchSeatOptions = async () => {
  seatLoading.value = true;
  try {
    const params: Record<string, any> = {
      Pageindex: 1,
      PageSize: 1000,
      Seatnmae: warehouseSearchForm.seat || undefined,
    };
    if (selectedWarehouseId.value) {
      params.Warehouseid = selectedWarehouseId.value;
    }
    if (selectedReservoirId.value) {
      params.Reservoirid = selectedReservoirId.value;
    }
    const res = await https.Reads.get("/Warehouse/Seatlist", { params });
    const payload = res.data || {};
    const rawList = payload.data ?? payload.Data ?? [];
    seatOptions.value = Array.isArray(rawList)
      ? rawList.map((item: any) => normalizeSeatOption(item))
      : [];
  } catch (error) {
    console.error("获取库位列表失败", error);
    seatOptions.value = [];
  } finally {
    seatLoading.value = false;
  }
};

const handleOpenWarehouseDialog = (detailIndex: number) => {
  currentWarehouseDetailIndex.value = detailIndex;
  warehouseDialogVisible.value = true;
  selectedWarehouseId.value = null;
  selectedReservoirId.value = null;
  selectedSeatId.value = null;
  selectedWarehouseOption.value = null;
  selectedReservoirOption.value = null;
  selectedSeatOption.value = null;
  warehouseSearchForm.warehouse = "";
  warehouseSearchForm.reservoir = "";
  warehouseSearchForm.seat = "";
  fetchWarehouseOptions();
  fetchReservoirOptions();
  fetchSeatOptions();
};

const handleWarehouseSearchSubmit = (
  type: "warehouse" | "reservoir" | "seat"
) => {
  if (type === "warehouse") {
    fetchWarehouseOptions();
  } else if (type === "reservoir") {
    fetchReservoirOptions();
  } else {
    fetchSeatOptions();
  }
};

const selectWarehouseOption = (option: WarehouseOption) => {
  selectedWarehouseId.value = option.id;
  selectedWarehouseOption.value = option;
  selectedReservoirId.value = null;
  selectedReservoirOption.value = null;
  selectedSeatId.value = null;
  selectedSeatOption.value = null;
  fetchReservoirOptions();
  fetchSeatOptions();
};

const selectReservoirOption = (option: ReservoirOption) => {
  selectedReservoirId.value = option.id;
  selectedReservoirOption.value = option;
  selectedSeatId.value = null;
  selectedSeatOption.value = null;
  fetchSeatOptions();
};

const selectSeatOption = (option: SeatOption) => {
  selectedSeatId.value = option.id;
  selectedSeatOption.value = option;
};

const handleWarehouseConfirm = () => {
  if (
    currentWarehouseDetailIndex.value === null ||
    !selectedWarehouseOption.value ||
    !selectedReservoirOption.value ||
    !selectedSeatOption.value
  ) {
    ElMessage.warning("请完整选择仓库、库区和库位");
    return;
  }
  const detail = formModel.detail[currentWarehouseDetailIndex.value];
  if (!detail) {
    ElMessage.error("无法定位当前明细，请重新打开仓库选择");
    return;
  }
  detail.warehouseName = `${selectedWarehouseOption.value.name} ${selectedReservoirOption.value.name} ${selectedSeatOption.value.name}`;
  detail.warehousePrincipal = selectedWarehouseOption.value.principal || "";
  warehouseDialogVisible.value = false;
};

// 添加明细
const handleAddDetail = () => {
  formModel.detail.push({
    inboundOrderId: 0,
    materialName: "",
    materialNo: "",
    specification: "",
    unit: "",
    productionDate: null,
    expiryDate: null,
    batchNo: "",
    inboundQuantity: 0,
    warehouseName: "",
    warehousePrincipal: "",
  });
};

// 删除明细
const handleRemoveDetail = (index: number) => {
  formModel.detail.splice(index, 1);
};

// 初始化编辑数据
const initEditData = () => {
  const editDataStr = route.query.editData as string;
  if (editDataStr) {
    try {
      const editData = JSON.parse(decodeURIComponent(editDataStr));
      editId.value = editData.id;
      isEditMode.value = true;
      isSystemNo.value = editData.isSystemNo || false;

      // 填充主表数据
      formModel.inboundOrderNo = editData.inboundOrderNo || "";
      formModel.inboundOrderName = editData.inboundOrderName || "";
      formModel.inboundDate = editData.inboundDate
        ? editData.inboundDate.split("T")[0]
        : null;
      formModel.purchaseOrderName = editData.purchaseOrderName || "";
      formModel.purchaseOrderNo = editData.purchaseOrderNo || "";
      formModel.supplierName = editData.supplierName || null;
      formModel.materialInspectName = editData.materialInspectName || "";
      formModel.materialInspectNo = editData.materialInspectNo || "";
      formModel.materialName = editData.materialName || "";
      formModel.materialCode = editData.materialCode || "";
      formModel.specification = editData.specification || "";
      formModel.unit = editData.unit || "";
      formModel.remark = editData.remark || "";

      // 填充明细数据
      if (editData.detail && Array.isArray(editData.detail)) {
        formModel.detail = editData.detail.map((item: any) => ({
          id: item.id || null,
          inboundOrderId: item.inboundOrderId || 0,
          materialName: item.materialName || "",
          materialNo: item.materialNo || "",
          specification: item.specification || "",
          unit: item.unit || "",
          productionDate: item.productionDate
            ? item.productionDate.split("T")[0]
            : null,
          expiryDate: item.expiryDate ? item.expiryDate.split("T")[0] : null,
          batchNo: item.batchNo || "",
          inboundQuantity: item.inboundQuantity || 0,
          warehouseName: item.warehouseName || "",
          warehousePrincipal: item.warehousePrincipal || "",
        }));
      }
    } catch (error) {
      console.error("解析编辑数据失败:", error);
      ElMessage.error("加载编辑数据失败，请重新操作");
      router.push("/PurchaseInboundList");
    }
  }
};

// 取消
const handleCancel = () => {
  router.push("/PurchaseInboundList");
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  // 验证明细
  if (formModel.detail.length === 0) {
    ElMessage.warning("至少需要添加一条入库明细");
    return;
  }

  const normalize = (value?: string | null) => (value ?? "").trim();

  // 验证明细必填字段
  for (let i = 0; i < formModel.detail.length; i++) {
    const detail = formModel.detail[i];
    if (!detail) {
      ElMessage.warning(`第${i + 1}条明细数据异常，请重新填写`);
      return;
    }
    if (!normalize(detail.materialName) || !normalize(detail.materialNo)) {
      ElMessage.warning(`第${i + 1}条明细的物料名称和物料编号不能为空`);
      return;
    }
    if (!normalize(detail.batchNo)) {
      ElMessage.warning(`第${i + 1}条明细的批次号不能为空`);
      return;
    }
    if (detail.inboundQuantity <= 0) {
      ElMessage.warning(`第${i + 1}条明细的入库数量必须大于0`);
      return;
    }
  }

  await formRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }

    submitLoading.value = true;

    try {
      if (isEditMode.value && editId.value) {
        // 编辑模式
        const requestData = {
          id: editId.value,
          inboundOrderNo: formModel.inboundOrderNo,
          isSystemNo: isSystemNo.value,
          inboundOrderName: formModel.inboundOrderName,
          inboundDate: formModel.inboundDate
            ? new Date(formModel.inboundDate + "T00:00:00").toISOString()
            : null,
          purchaseOrderName: formModel.purchaseOrderName || "",
          purchaseOrderNo: formModel.purchaseOrderNo || "",
          supplierName: formModel.supplierName || null,
          materialInspectName: formModel.materialInspectName || "",
          materialInspectNo: formModel.materialInspectNo || "",
          materialName: formModel.materialName || "",
          materialCode: formModel.materialCode || "",
          specification: formModel.specification || "",
          unit: formModel.unit || "",
          remark: formModel.remark || "",
          detail: formModel.detail.map((item) => ({
            id: item.id || null,
            inboundOrderId: editId.value || 0,
            materialName: item.materialName,
            materialNo: item.materialNo,
            specification: item.specification || "",
            unit: item.unit || "",
            productionDate: item.productionDate
              ? new Date(item.productionDate + "T00:00:00").toISOString()
              : null,
            expiryDate: item.expiryDate
              ? new Date(item.expiryDate + "T00:00:00").toISOString()
              : null,
            batchNo: item.batchNo || "",
            inboundQuantity: item.inboundQuantity,
            warehouseName: item.warehouseName || "",
            warehousePrincipal: item.warehousePrincipal || "",
          })),
        };

        const response = await https.Writes.put(
          "/Warehouse/PurchasingSystemUpdate",
          requestData
        );

        if (response.data.code === 1) {
          ElMessage.success(response.data.msg || "编辑采购入库成功");
          router.push("/PurchaseInboundList");
        } else {
          ElMessage.error(response.data.msg || "编辑采购入库失败");
        }
      } else {
        // 新增模式
        const requestData = {
          inboundOrderNo: formModel.inboundOrderNo,
          isSystemNo: isSystemNo.value,
          inboundOrderName: formModel.inboundOrderName,
          inboundDate: formModel.inboundDate
            ? new Date(formModel.inboundDate + "T00:00:00").toISOString()
            : null,
          purchaseOrderName: formModel.purchaseOrderName || "",
          purchaseOrderNo: formModel.purchaseOrderNo || "",
          supplierName: formModel.supplierName || null,
          materialInspectName: formModel.materialInspectName || "",
          materialInspectNo: formModel.materialInspectNo || "",
          materialName: formModel.materialName || "",
          materialCode: formModel.materialCode || "",
          specification: formModel.specification || "",
          unit: formModel.unit || "",
          remark: formModel.remark || "",
          detail: formModel.detail.map((item) => ({
            inboundOrderId: 0,
            materialName: item.materialName,
            materialNo: item.materialNo,
            specification: item.specification || "",
            unit: item.unit || "",
            productionDate: item.productionDate
              ? new Date(item.productionDate + "T00:00:00").toISOString()
              : null,
            expiryDate: item.expiryDate
              ? new Date(item.expiryDate + "T00:00:00").toISOString()
              : null,
            batchNo: item.batchNo || "",
            inboundQuantity: item.inboundQuantity,
            warehouseName: item.warehouseName || "",
            warehousePrincipal: item.warehousePrincipal || "",
          })),
        };

        const response = await https.Writes.post(
          "/Warehouse/PurchasingSystemAdd",
          requestData
        );

        if (response.data.code === 1) {
          ElMessage.success(response.data.msg || "新增采购入库成功");
          router.push("/PurchaseInboundList");
        } else {
          ElMessage.error(response.data.msg || "新增采购入库失败");
        }
      }
    } catch (error: any) {
      console.error("操作失败:", error);
      const errorMsg =
        error?.response?.data?.msg || error?.message || "请求失败，请稍后再试";
      ElMessage.error(errorMsg);
    } finally {
      submitLoading.value = false;
    }
  });
};

// 格式化来料检验日期
const formatInspectionDate = (value: string | null | undefined): string => {
  if (!value) return "-";
  if (typeof value === "string") {
    const [datePart] = value.split("T");
    return datePart || "-";
  }
  return "-";
};

// 获取来料检验列表
const fetchInspectionList = async () => {
  inspectionListLoading.value = true;
  try {
    const params: Record<string, any> = {
      pageindex: inspectionPagination.pageIndex,
      pagesize: inspectionPagination.pageSize,
    };
    if (inspectionSearchForm.keyword.trim()) {
      params.keyword = inspectionSearchForm.keyword.trim();
    }
    if (inspectionSearchForm.materialKeyword.trim()) {
      // 物料编号/名称搜索，先查询物料列表获取物料ID
      try {
        const materialKeyword = inspectionSearchForm.materialKeyword.trim();
        const materialRes = await https.Reads.get("/Material/MaterialGetList", {
          params: {
            pageindex: 1,
            pagesize: 100,
            materialname: materialKeyword,
            materialcode: materialKeyword,
          },
        });
        const materialPayload = materialRes?.data ?? {};
        if (materialPayload.code === 1) {
          const materialList =
            materialPayload.data ?? materialPayload.Data ?? [];
          if (materialList.length > 0) {
            // 精确匹配物料编号或名称
            const matchedMaterial = materialList.find(
              (m: any) =>
                (m.materialcode || m.Materialcode || "").toLowerCase() ===
                  materialKeyword.toLowerCase() ||
                (m.materialname || m.Materialname || "").toLowerCase() ===
                  materialKeyword.toLowerCase() ||
                (m.materialcode || m.Materialcode || "").includes(
                  materialKeyword
                ) ||
                (m.materialname || m.Materialname || "").includes(
                  materialKeyword
                )
            );
            const materialId = matchedMaterial
              ? matchedMaterial.id ?? matchedMaterial.Id
              : materialList[0]?.id ?? materialList[0]?.Id;
            if (materialId) {
              params.materialid = materialId;
            }
          } else {
            // 如果没有找到物料，设置一个不存在的ID，这样查询结果为空
            params.materialid = -1;
          }
        }
      } catch (error) {
        console.error("查询物料列表失败", error);
        // 如果查询物料失败，继续使用其他条件查询
      }
    }
    if (inspectionSearchForm.incomingDate) {
      // 来料日期搜索，需要转换为日期格式
      params.incomingdate = inspectionSearchForm.incomingDate;
    }
    const res = await https.Reads.get("/IncomingInspection/List", { params });
    const payload = res?.data ?? {};
    const code = payload.code ?? payload.Code ?? 0;

    if (code === 1) {
      const list = payload.data ?? payload.Data ?? [];
      inspectionTableData.value = list.map((item: any) => ({
        id: item.id ?? item.Id ?? 0,
        inspectioncode: item.inspectioncode ?? item.Inspectioncode ?? "",
        inspectionname: item.inspectionname ?? item.Inspectionname ?? "",
        incomingdate: item.incomingdate ?? item.Incomingdate ?? null,
        inspectiondate: item.inspectiondate ?? item.Inspectiondate ?? null,
        materialname: item.materialname ?? item.Materialname ?? "",
        materialcode: item.materialcode ?? item.Materialcode ?? "",
        specification: item.specification ?? item.Specification ?? "",
        unit: item.unit ?? item.Unit ?? "",
        batchno: item.batchno ?? item.Batchno ?? "",
      }));
      inspectionPagination.total =
        payload.totalCount ??
        payload.TotalCount ??
        inspectionTableData.value.length;
    } else {
      ElMessage.error(payload.msg ?? payload.Msg ?? "获取来料检验列表失败");
      inspectionTableData.value = [];
      inspectionPagination.total = 0;
    }
  } catch (error: any) {
    console.error("获取来料检验列表失败", error);
    const msg =
      error?.response?.data?.msg ||
      error?.message ||
      "获取来料检验列表失败，请稍后再试";
    ElMessage.error(msg);
    inspectionTableData.value = [];
    inspectionPagination.total = 0;
  } finally {
    inspectionListLoading.value = false;
  }
};

// 打开来料检验选择对话框
const handleOpenInspectionDialog = () => {
  inspectionDialogVisible.value = true;
  inspectionPagination.pageIndex = 1;
  selectedInspectionId.value = null;
  selectedInspectionRow.value = null;
  inspectionSearchForm.keyword = "";
  inspectionSearchForm.materialKeyword = "";
  inspectionSearchForm.incomingDate = null;
  fetchInspectionList();
};

// 来料检验搜索
const handleInspectionSearch = () => {
  inspectionPagination.pageIndex = 1;
  fetchInspectionList();
};

// 来料检验重置
const handleInspectionReset = () => {
  inspectionSearchForm.keyword = "";
  inspectionSearchForm.materialKeyword = "";
  inspectionSearchForm.incomingDate = null;
  handleInspectionSearch();
};

// 来料检验分页变化
const handleInspectionPageChange = (page: number) => {
  inspectionPagination.pageIndex = page;
  fetchInspectionList();
};

// 来料检验行选择
const handleInspectionRowSelect = (row: IncomingInspectionDto) => {
  selectedInspectionId.value = row.id;
  selectedInspectionRow.value = row;
};

// 来料检验确认
const handleInspectionConfirm = () => {
  if (!selectedInspectionRow.value) {
    ElMessage.warning("请选择来料检验单");
    return;
  }
  const row = selectedInspectionRow.value;

  // 赋值给基础信息
  formModel.materialInspectName = row.inspectionname || "";
  formModel.materialInspectNo = row.inspectioncode || "";

  // 赋值给基础信息的物料字段（显示用）
  formModel.materialName = row.materialname || "";
  formModel.materialCode = row.materialcode || "";
  formModel.specification = row.specification || "";
  formModel.unit = row.unit || "";

  // 赋值给入库明细：如果明细列表为空，则自动创建一条明细；如果已有明细，则更新所有明细的物料信息
  if (formModel.detail.length === 0) {
    // 如果没有明细，自动创建一条并赋值
    formModel.detail.push({
      inboundOrderId: 0,
      materialName: row.materialname || "",
      materialNo: row.materialcode || "",
      specification: row.specification || "",
      unit: row.unit || "",
      productionDate: null,
      expiryDate: null,
      batchNo: row.batchno || "",
      inboundQuantity: 0,
      warehouseName: "",
      warehousePrincipal: "",
    });
  } else {
    // 如果已有明细，更新所有明细的物料信息（物料名称、物料编号、规格型号、单位）
    formModel.detail.forEach((detail) => {
      detail.materialName = row.materialname || "";
      detail.materialNo = row.materialcode || "";
      detail.specification = row.specification || "";
      detail.unit = row.unit || "";
      // 如果批次号为空，则使用来料检验单的批次号
      if (!detail.batchNo && row.batchno) {
        detail.batchNo = row.batchno;
      }
    });
  }

  inspectionDialogVisible.value = false;
  ElMessage.success("来料检验单信息已填充");
};

// 页面加载时初始化
onMounted(() => {
  initEditData();
});
</script>

<style scoped>
.purchase-inbound-add-page {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  padding-bottom: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 面包屑卡片 */
.breadcrumb-card {
  border-radius: 14px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.25);
  color: #fff;
}

.breadcrumb-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.breadcrumb-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.breadcrumb-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  flex-shrink: 0;
}

.breadcrumb-subtitle {
  margin: 0;
  font-size: 13px;
  opacity: 0.9;
  font-weight: 400;
}

.breadcrumb-heading {
  margin: 4px 0 0;
  font-size: 22px;
  font-weight: 600;
  line-height: 1.2;
}

.breadcrumb-card :deep(.el-breadcrumb) {
  font-size: 14px;
}

.breadcrumb-card :deep(.el-breadcrumb__inner) {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
}

.breadcrumb-card :deep(.el-breadcrumb__inner.is-link) {
  color: rgba(255, 255, 255, 0.9);
  transition: color 0.3s ease;
}

.breadcrumb-card :deep(.el-breadcrumb__inner.is-link:hover) {
  color: #fff;
}

.breadcrumb-card :deep(.el-breadcrumb__separator) {
  color: rgba(255, 255, 255, 0.7);
}

.form-card {
  padding: 32px 40px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  background: #ffffff;
  transition: all 0.3s ease;
}

.form-card:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
}

.page-header {
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 2px solid #f0f2f5;
  position: relative;
}

.page-header::after {
  content: "";
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 80px;
  height: 2px;
  background: linear-gradient(90deg, #409eff, #66b1ff);
  border-radius: 2px;
}

.page-header__content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.page-header__title {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
}

.page-header__icon-wrapper {
  width: 56px;
  height: 56px;
  border-radius: 14px;
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  flex-shrink: 0;
  transition: all 0.3s ease;
}

.page-header__icon-wrapper:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}

.page-header__text {
  flex: 1;
}

.page-header__text h2 {
  margin: 0;
  font-size: 26px;
  font-weight: 600;
  color: #1f2d3d;
  line-height: 1.3;
}

.page-header__desc {
  margin: 6px 0 0;
  font-size: 14px;
  color: #909399;
  line-height: 1.4;
}

.page-header__tag {
  font-size: 14px;
  padding: 10px 20px;
  border-radius: 20px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.tag-icon {
  font-size: 16px;
}

.purchase-inbound-form {
  margin-top: 24px;
}

.form-section {
  margin-bottom: 32px;
  padding: 28px 32px;
  background: linear-gradient(135deg, #fafbfc 0%, #f5f7fa 100%);
  border: 1px solid #e4e7ed;
  border-radius: 14px;
  box-shadow: 0 2px 12px rgba(31, 45, 61, 0.06);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.form-section::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #409eff, #66b1ff, #85c1ff);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.form-section:hover {
  box-shadow: 0 4px 20px rgba(31, 45, 61, 0.1);
  border-color: #c0c4cc;
  transform: translateY(-2px);
}

.form-section:hover::before {
  opacity: 1;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f2f5;
}

.section-header__main {
  display: flex;
  gap: 14px;
  align-items: center;
}

.section-header__icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: linear-gradient(135deg, #f0f5ff, #e6f0ff);
  display: flex;
  justify-content: center;
  align-items: center;
  color: #409eff;
  font-size: 22px;
  flex-shrink: 0;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
  transition: all 0.3s ease;
}

.section-header__icon:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.25);
}

.section-header__icon--detail {
  background: linear-gradient(135deg, #fff7e6, #ffecc7);
  color: #e6a23c;
  box-shadow: 0 2px 8px rgba(230, 162, 60, 0.15);
}

.section-header__icon--detail:hover {
  box-shadow: 0 4px 12px rgba(230, 162, 60, 0.25);
}

.section-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2d3d;
  line-height: 1.4;
}

.section-subtitle {
  margin: 4px 0 0;
  font-size: 13px;
  color: #909399;
  line-height: 1.4;
}

.section-header__actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.detail-count-tag {
  margin-right: 12px;
  font-weight: 500;
}

.add-detail-btn {
  border-radius: 8px;
  font-weight: 500;
  padding: 10px 20px;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.25);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.add-detail-btn:hover {
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.35);
  transform: translateY(-2px);
}

.system-code-field {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 16px;
  border: 1px dashed #dcdfe6;
  border-radius: 12px;
  background: linear-gradient(135deg, #fdfdff 0%, #f4f8ff 100%);
  box-shadow: inset 0 0 0 1px rgba(64, 158, 255, 0.05);
}

.system-code-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.system-code-input :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: box-shadow 0.3s ease;
}

.system-code-input :deep(.el-input__wrapper:hover),
.system-code-input :deep(.el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px #90c2ff inset, 0 0 0 2px rgba(64, 158, 255, 0.2) inset;
}

.system-code-prefix {
  color: #409eff;
  font-size: 16px;
}

.system-code-btn {
  color: #6085b3;
  transition: color 0.2s ease, transform 0.2s ease;
}

.system-code-btn:hover:not(:disabled) {
  color: #409eff;
  transform: translateY(-1px);
}

.system-code-btn:disabled {
  color: #c0c4cc;
}

.system-code-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.system-code-controls :deep(.el-switch) {
  --el-switch-off-color: #dcdfe6;
  --el-switch-on-color: #409eff;
}

.system-code-status {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #909399;
  padding: 4px 10px;
  border-radius: 999px;
  background: #f4f6fa;
  border: 1px solid #e4e7ed;
}

.system-code-status.is-auto {
  color: #409eff;
  background: #ecf5ff;
  border-color: #c6e2ff;
}

.system-code-hint {
  margin: 0;
  font-size: 12px;
  color: #8f98a8;
  line-height: 1.4;
}

.input-icon {
  color: #909399;
  cursor: pointer;
  transition: color 0.3s ease;
}

.input-icon:hover {
  color: #409eff;
}

.batch-select-field {
  display: flex;
  gap: 8px;
  align-items: center;
}

.batch-select-field .el-input {
  flex: 1;
}

.batch-select-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.supplier-select-field {
  display: flex;
  gap: 8px;
  align-items: center;
}

.supplier-select-field .el-input {
  flex: 1;
}

.supplier-select-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.warehouse-select-field {
  display: flex;
  gap: 8px;
  align-items: center;
}

.warehouse-select-field .el-input {
  flex: 1;
}

.warehouse-select-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.inspection-select-field {
  display: flex;
  gap: 8px;
  align-items: center;
}

.inspection-select-field .el-input {
  flex: 1;
}

.inspection-select-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.inspection-dialog-toolbar {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.inspection-dialog-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-total {
  font-size: 14px;
  color: #606266;
}

.warehouse-dialog-summary {
  margin-bottom: 12px;
  font-size: 14px;
  color: #606266;
}

.warehouse-dialog-columns {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.warehouse-column {
  border: 1px solid #ebeef5;
  border-radius: 10px;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  background: #fafbfc;
}

.column-title {
  font-weight: 600;
  color: #303133;
}

.column-list {
  max-height: 360px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fff;
}

.column-option {
  padding: 10px 12px;
  cursor: pointer;
  border-bottom: 1px solid #f2f3f5;
  transition: background 0.2s ease;
}

.column-option:last-child {
  border-bottom: none;
}

.column-option:hover {
  background: #f5f7fa;
}

.column-option.active {
  background: #ecf5ff;
  color: #409eff;
  font-weight: 600;
}

.column-search-icon {
  cursor: pointer;
}

.warehouse-dialog .el-empty {
  padding: 20px 0;
}

.supplier-dialog-toolbar {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.supplier-dialog-toolbar .el-input {
  flex: 1;
}

.supplier-dialog-toolbar .el-select {
  width: 220px;
}

.supplier-dialog-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.batch-dialog-toolbar {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.batch-dialog-toolbar .el-input {
  flex: 1;
}

.batch-dialog-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

/* 入库明细区域样式 */
.detail-section {
  background: linear-gradient(135deg, #fafbfc 0%, #f5f7fa 100%);
}

.detail-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-item {
  background: #ffffff;
  border: 1px solid #e4e7ed;
  border-radius: 14px;
  padding: 24px 28px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.detail-item::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: linear-gradient(180deg, #409eff, #66b1ff);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.detail-item:hover {
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
  border-color: #c0c4cc;
  transform: translateY(-2px);
}

.detail-item:hover::before {
  opacity: 1;
}

.detail-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f0f2f5;
}

.detail-item-number-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
}

.detail-item-number {
  font-size: 15px;
  font-weight: 600;
  color: #409eff;
  background: linear-gradient(135deg, #f0f5ff, #e6f0ff);
  padding: 6px 16px;
  border-radius: 20px;
  border: 1px solid #d6e8ff;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.15);
}

.detail-item-tag {
  font-size: 12px;
}

.delete-detail-btn {
  color: #f56c6c;
  font-size: 14px;
  font-weight: 500;
  padding: 8px 12px;
  transition: all 0.3s ease;
}

.delete-detail-btn:hover {
  color: #f78989;
  background-color: rgba(245, 108, 108, 0.1);
  border-radius: 6px;
}

.detail-form {
  margin-top: 8px;
}

.detail-form :deep(.el-form-item) {
  margin-bottom: 18px;
}

.detail-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  font-size: 14px;
}

.detail-form :deep(.el-form-item.is-required .el-form-item__label::before) {
  color: #f56c6c;
  margin-right: 4px;
}

.empty-detail {
  margin: 60px 0;
  padding: 60px 40px;
  background: #fafbfc;
  border-radius: 12px;
  border: 2px dashed #e4e7ed;
  transition: all 0.3s ease;
}

.empty-detail:hover {
  border-color: #c0c4cc;
  background: #f5f7fa;
}

.empty-detail :deep(.el-empty__description) {
  color: #909399;
  font-size: 14px;
  margin-top: 16px;
}

.empty-detail :deep(.el-empty__image) {
  opacity: 0.6;
}

.form-actions {
  margin-top: 40px;
  padding-top: 28px;
  border-top: 2px solid #f0f2f5;
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  position: relative;
}

.form-actions::before {
  content: "";
  position: absolute;
  top: -2px;
  right: 0;
  width: 100px;
  height: 2px;
  background: linear-gradient(90deg, transparent, #409eff);
  border-radius: 2px;
}

.form-actions .el-button {
  min-width: 120px;
  height: 44px;
  border-radius: 10px;
  font-weight: 500;
  font-size: 15px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.cancel-btn {
  border-color: #dcdfe6;
  color: #606266;
}

.cancel-btn:hover {
  border-color: #c0c4cc;
  color: #409eff;
  background-color: #f5f7fa;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.submit-btn {
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  background: linear-gradient(135deg, #409eff, #66b1ff);
  border: none;
}

.submit-btn:hover {
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.4);
  transform: translateY(-2px);
  background: linear-gradient(135deg, #66b1ff, #85c1ff);
}

.submit-btn:active {
  transform: translateY(0);
}

/* 表单输入框美化 */
:deep(.el-input__wrapper) {
  border-radius: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2) inset, 0 0 0 1px #409eff inset;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  font-size: 14px;
}

:deep(.el-form-item.is-required .el-form-item__label::before) {
  color: #f56c6c;
  margin-right: 4px;
  font-weight: 600;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
  transition: all 0.3s ease;
  border-color: #dcdfe6;
}

:deep(.el-textarea__inner:hover) {
  border-color: #c0c4cc;
}

:deep(.el-textarea__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.el-date-editor) {
  border-radius: 8px;
}

:deep(.el-date-editor .el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-switch) {
  --el-switch-on-color: #409eff;
}

:deep(.el-switch__core) {
  border-radius: 12px;
}

/* 表格内输入框样式 */
.detail-table :deep(.el-input__wrapper) {
  border-radius: 4px;
}

.detail-table :deep(.el-input-number) {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .purchase-inbound-add-page {
    padding: 12px;
  }

  .form-card {
    padding: 20px;
  }

  .breadcrumb-content {
    flex-direction: column;
    align-items: flex-start;
  }

  .page-header__content {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .page-header__title {
    width: 100%;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .section-header__actions {
    width: 100%;
    justify-content: space-between;
  }

  .detail-item {
    padding: 20px;
  }

  .form-actions {
    flex-direction: column;
  }

  .form-actions .el-button {
    width: 100%;
  }
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.form-section {
  animation: fadeInUp 0.5s ease-out;
}

.detail-item {
  animation: fadeInUp 0.4s ease-out;
}

/* 滚动条美化 */
:deep(.el-scrollbar__bar) {
  opacity: 0.6;
}

/* 选择器美化 */
:deep(.el-select .el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-select:hover .el-input__wrapper) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}
</style>
